package com.bearingnavi.android.services;

import android.content.res.Resources;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

import com.bearingnavi.android.overlays.ArrowOverlay;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class SensorService implements SensorEventListener {
	
	private ArrowOverlay arrowOverlay;
	private float lastTokenSensorAngle = 0;
	private LocationService locationService;
	private MapView mapView;
	private Resources resources;
	
	public SensorService(LocationService locationService, MapView mapView, Resources resources) {
		
		this.mapView = mapView;
		this.locationService = locationService;
		this.resources = resources;
	}
	
	public void onCurrentPositionChanged(GeoPoint geoPoint) {
		
		if (arrowOverlay != null) {
			
			drawArrowOverlay(geoPoint, arrowOverlay.getDegrees());	
		}
	}
	
	private void drawArrowOverlay(GeoPoint geoPoint, float degrees) {

		if (arrowOverlay == null) {
			arrowOverlay = new ArrowOverlay(geoPoint, resources, degrees);
			mapView.getOverlays().add(arrowOverlay);
		}
		
		arrowOverlay.setDegrees(degrees);
		arrowOverlay.setGeoPoint(geoPoint);
	}
	
	public void onSensorChanged(SensorEvent event) {
		
		if (locationService.getLastGeoPoint() != null) {
			
			
			float sensorAngle = event.values[0]+LocationService.getDeclination();
			
			if (Math.abs(sensorAngle-lastTokenSensorAngle) > 5) {
				
				
				drawArrowOverlay(locationService.getLastGeoPoint(), sensorAngle);
				
				mapView.invalidate();
				
				lastTokenSensorAngle = sensorAngle;
			}
			
		}
		
	}
	
	public void onAccuracyChanged(Sensor sensor, int accuracy) {	}
	
}
